package cn.doctorpda.conference.view.bannerview;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

import cn.doctorpda.conference.R;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.User;
import cn.doctorpda.conference.ui.recommend.RecommendFragment;
import cn.doctorpda.conference.utils.ImageUtils;
import cn.doctorpda.conference.utils.ScreenUtils;

public class Kanner extends FrameLayout {
    private int count;
    //    private ImageLoader mImageLoader;
    private List<ImageView> imageViews;
    private Context context;
    private ViewPager vp;
    private boolean isAutoPlay;
    private int currentItem;
    private int delayTime;
//    private List<String> imgRes;

    //    private LinearLayout ll_dot;
//    private List<ImageView> iv_dots;
    private Handler handler = new Handler();
//    private DisplayImageOptions options;

    public Kanner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
//        initImageLoader(context);
        initData();
    }

    public Kanner(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Kanner(Context context) {
        this(context, null);
    }


    private OnKannerListener listener;

    public void setOnKannerListener(OnKannerListener listener) {
        this.listener = listener;
    }

    public interface OnKannerListener {
        void setOnKannerListener(int pos);
    }


    private void initData() {
        imageViews = new ArrayList<ImageView>();
//        iv_dots = new ArrayList<ImageView>();
        delayTime = 5000;
    }

    public void setImagesUrl(String[] imagesUrl) {
        initLayout();
        initImgFromNet(imagesUrl);
        showTime();
    }

    public void setImagesRes(int[] imagesRes) {
        initLayout();
        initImgFromRes(imagesRes);
        showTime();
    }

    private void initLayout() {
        imageViews.clear();
        View view = LayoutInflater.from(context).inflate(
                R.layout.kanner_layout, this, true);
        vp = (ViewPager) view.findViewById(R.id.vp);
        vp.setClipToPadding(false);
        //为了16：9
//        int padding = ScreenUtils.getScreenWidth(context) - ScreenUtils.getScreenHeight(context) / 3 / 9 * 16;

        vp.setPadding((int)(ScreenUtils.getScreenWidth(context)*3.5f / 16), 0, (int)(ScreenUtils.getScreenWidth(context)*3.5f / 16), 0);
        vp.setPageMargin(15);

//        vp.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ScreenUtils.getScreenHeight(context) / 3));

//        ll_dot = (LinearLayout) view.findViewById(R.id.ll_dot);
//        ll_dot.removeAllViews();
    }

    private void initImgFromRes(int[] imagesRes) {
        count = imagesRes.length;
        for (int i = 0; i < count; i++) {
            ImageView iv_dot = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
//            iv_dot.setImageResource(R.drawable.dot_blur);
//            ll_dot.addView(iv_dot, params);
//            iv_dots.add(iv_dot);
        }
//        iv_dots.get(0).setImageResource(R.drawable.dot_focus);

        for (int i = 0; i <= count + 1; i++) {
            ImageView iv = new ImageView(context);
            iv.setScaleType(ScaleType.FIT_XY);
//            iv.setBackgroundResource(R.drawable.loading);
            if (i == 0) {
                iv.setImageResource(imagesRes[count - 1]);
            } else if (i == count + 1) {
                iv.setImageResource(imagesRes[0]);
            } else {
                iv.setImageResource(imagesRes[i - 1]);
            }
            imageViews.add(iv);
        }
    }

    private void initImgFromNet(String[] imagesUrl) {
        count = imagesUrl.length;

        for (int i = 0; i < count; i++) {
            ImageView iv_dot = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
//            iv_dot.setImageResource(R.drawable.dot_blur);
//            ll_dot.addView(iv_dot, params);
//            iv_dots.add(iv_dot);
        }
//        iv_dots.get(0).setImageResource(R.drawable.dot_focus);

        for (int i = 0; i <= count + 1; i++) {
            ImageView iv = new ImageView(context);
            iv.setScaleType(ScaleType.FIT_XY);
//            iv.setBackgroundResource(R.mipmap.loading);
            if (i == 0) {
                ImageUtils.loadImage(context, imagesUrl[count - 1], iv);
            } else if (i == count + 1) {
                ImageUtils.loadImage(context, imagesUrl[0], iv);
            } else {
                ImageUtils.loadImage(context, imagesUrl[i - 1], iv);
            }
            imageViews.add(iv);
        }
    }

    private void showTime() {
        vp.setAdapter(new KannerPagerAdapter());
        vp.setFocusable(true);
        vp.setCurrentItem(1);
        currentItem = 1;
        vp.addOnPageChangeListener(new MyOnPageChangeListener());
        startPlay();
    }

    private void startPlay() {
        isAutoPlay = true;
        handler.postDelayed(task, 5000);
    }

//    public void initImageLoader(Context context) {
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
//                context).threadPriority(Thread.NORM_PRIORITY - 2)
//                .denyCacheImageMultipleSizesInMemory()
//                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
//                .tasksProcessingOrder(QueueProcessingType.LIFO)
//                .writeDebugLogs().build();
//        ImageLoader.getInstance().init(config);
//        options = new DisplayImageOptions.Builder()
//                .cacheInMemory(true)
//                .cacheOnDisk(true)
//                .build();
//        mImageLoader = ImageLoader.getInstance();
//    }

    private final Runnable task = new Runnable() {

        @Override
        public void run() {
            if (isAutoPlay) {
                currentItem = currentItem % (count + 1) + 1;
                if (currentItem == 1) {
                    vp.setCurrentItem(currentItem, false);
                    handler.post(task);
                } else {
                    vp.setCurrentItem(currentItem);
                    handler.postDelayed(task, 5000);
                }
            } else {
                handler.postDelayed(task, 7000);
            }
        }
    };

    class KannerPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imageViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = imageViews.get(position);

            container.addView(imageViews.get(position));

            imageView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    try {
                        listener.setOnKannerListener(position);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

//                    Intent i = new Intent(context, ViewPagerActivity.class);
//                    i.putExtra("imv_position", position);
//                    i.putExtra("imv_count", count);
//                    context.startActivity(i);
                }
            });
            return imageViews.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(imageViews.get(position));
        }

    }

    class MyOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

            switch (arg0) {
                case 1://good
                    if (RecommendFragment.mSwipe != null)
                        RecommendFragment.mSwipe.setEnabled(false);
                    isAutoPlay = false;
                    handler.removeCallbacksAndMessages(null);
                    break;
                case 2:
                    if (RecommendFragment.mSwipe != null)
                        RecommendFragment.mSwipe.setEnabled(true);
                    isAutoPlay = true;
                    break;
                case 0:
                    if (RecommendFragment.mSwipe != null)
                        RecommendFragment.mSwipe.setEnabled(true);
                    if (vp.getCurrentItem() == 0) {
                        vp.setCurrentItem(count, false);
                    } else if (vp.getCurrentItem() == count + 1) {
                        vp.setCurrentItem(1, false);
                    }
                    currentItem = vp.getCurrentItem();
                    isAutoPlay = true;
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
//            for (int i = 0; i < iv_dots.size(); i++) {
//                if (i == arg0 - 1) {
//                    iv_dots.get(i).setImageResource(R.drawable.dot_focus);
//                } else {
//                    iv_dots.get(i).setImageResource(R.drawable.dot_blur);
//                }
//            }
        }

    }

    public void removeCallbacksAndMessages() {
        handler.removeCallbacksAndMessages(null);
        context = null;
    }

}
